const express = require('express');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const auth = require('../middleware/auth');
const {
  successResponse,
  createdResponse,
  errorResponse,
  badRequestResponse,
  conflictResponse
} = require('../utils/response');

const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// 注册账号
router.post('/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;

    // 检查用户是否已存在
    const existingUser = await User.findOne({
      $or: [{ email }, { username }]
    });

    if (existingUser) {
      return conflictResponse(res, '用户名或邮箱已存在');
    }

    // 创建新用户
    const user = new User({ username, email, password });
    await user.save();

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user._id },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    createdResponse(res, '注册成功', {
      token,
      user: {
        id: user._id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 登录账号
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    // 查找用户
    const user = await User.findOne({ email });
    if (!user) {
      return badRequestResponse(res, '邮箱或密码错误');
    }

    // 验证密码
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return badRequestResponse(res, '邮箱或密码错误');
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user._id },
      JWT_SECRET,
      { expiresIn: '7d' }
    );

    successResponse(res, '登录成功', {
      token,
      user: {
        id: user._id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 注销账号 (删除用户)
router.delete('/logout', auth, async (req, res) => {
  try {
    await User.findByIdAndDelete(req.user._id);
    
    successResponse(res, '账号已成功注销');
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

// 获取当前用户信息
router.get('/profile', auth, async (req, res) => {
  try {
    successResponse(res, '获取用户信息成功', {
      user: {
        id: req.user._id,
        username: req.user.username,
        email: req.user.email,
        createdAt: req.user.createdAt,
        updatedAt: req.user.updatedAt
      }
    });
  } catch (error) {
    errorResponse(res, '服务器错误', 500, error.message);
  }
});

module.exports = router;
